package org.linlinjava.litemall.wx.web;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.linlinjava.litemall.core.util.ResponseUtil;
import org.linlinjava.litemall.core.validator.Order;
import org.linlinjava.litemall.core.validator.Sort;
import org.linlinjava.litemall.db.domain.LitemallBrand;
import org.linlinjava.litemall.db.domain.LitemallPointsRecord;
import org.linlinjava.litemall.db.domain.LitemallUser;
import org.linlinjava.litemall.db.service.LitemallBrandService;
import org.linlinjava.litemall.db.service.LitemallOrderService;
import org.linlinjava.litemall.db.service.LitemallPointsRecordService;
import org.linlinjava.litemall.db.service.LitemallUserService;
import org.linlinjava.litemall.wx.annotation.LoginUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.NotNull;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 积分控制器
 */
@RestController
@RequestMapping("/wx/point")
@Validated
public class WxPointController {
    private final Log logger = LogFactory.getLog(WxPointController.class);

    @Autowired
    LitemallPointsRecordService pointsRecordService;
    @Autowired
    LitemallUserService userService;

    @Autowired
    private LitemallOrderService orderService;

    /**
     * 积分列表
     * @param page 分页页数
     * @param limit 分页大小
     * @return 积分列表
     */
    @GetMapping("list")
    public Object list(@RequestParam(defaultValue = "1") Integer page,
                       @RequestParam(defaultValue = "10") Integer limit,
                       @RequestParam(defaultValue = "1") Integer type,
                       @RequestParam Integer userId) {
        List<LitemallPointsRecord> pointList = pointsRecordService.queryList(page,limit,userId,type);
        return ResponseUtil.okList(pointList);
    }

    /**
     * 积分详情
     *
     * @param id 品牌ID
     * @return 品牌详情
     */
    @GetMapping("detail")
    public Object detail(@NotNull Integer id) {
        LitemallPointsRecord pointsRecord = new LitemallPointsRecord();
        return ResponseUtil.ok(pointsRecord);
    }

    /**
     * 积分转账
     * @param fromId 支出用户
     * @param integral 支出多少积分
     * @param mobile 转给谁，通过手机号码找到收账用户
     * @return
     */
    @PostMapping("/transfer")
    public Object transfer(@RequestParam Integer fromId,@RequestParam Double integral,@RequestParam String mobile) throws Exception {
        pointsRecordService.transfer(fromId, integral, mobile);
        return ResponseUtil.ok();
    }

    /**
     * 积分提现
     * @param fromId 积分
     * @param integral 支出多少积分
     * @param relintegral 实际到账积分
     * @param sxfIntegral 手续费积分
     * @return
     */
    @PostMapping("/withdrawal")
    public Object withdrawal(@RequestParam Integer fromId,
                             @RequestParam Double integral,
                             @RequestParam Double relintegral,
                             @RequestParam Double sxfIntegral,
                            @RequestParam String yhk,
                             @RequestParam String yhklx,
                             @RequestParam String remark) throws Exception {
        // 是否消费满200
        int result = orderService.countByOrderUserId(fromId);
        if (result == 1){
            return ResponseUtil.fail(507,"您还不是有效会员");
        }

        //double p = integral * 0.95;
        double p2 = integral * 0.05;
        BigDecimal bg = new BigDecimal(integral - p2).setScale(2, RoundingMode.DOWN);
        BigDecimal bg2 = new BigDecimal(p2).setScale(2, RoundingMode.DOWN);

        if (bg.doubleValue() != relintegral){
            return ResponseUtil.fail(2,"实际到账积分不正确");
        }
        if (bg2.doubleValue() != sxfIntegral){
            return ResponseUtil.fail(3,"手续费不正确");
        }
        pointsRecordService.withdrawal(fromId, integral,yhk,yhklx,remark);
        return ResponseUtil.ok();
    }


    /**
     * 后台设置积分 （暂时不用）
     * @return
     */
    @PostMapping("/setting")
    public Object setting() throws Exception {
        System.out.println("11222");
        return ResponseUtil.ok(userService.findById(224));
    }

    /**
     * 根据用户id与积分变动类型查询积分变动记录
     * @return
     */
    @GetMapping("/pointlist")
    public Object pointlist(@RequestParam Integer userId,@RequestParam Integer type) throws Exception {
        return ResponseUtil.ok(pointsRecordService.selectPointListByType(userId, type));
    }

    /**
     * 提现界面返回积分
     * @param userId
     * @return
     * @throws Exception
     */
    @GetMapping("/withdrawalPre")
    public Object pointtixianpre(@LoginUser Integer userId) throws Exception {
        System.out.println(userId);
        // 总积分
        // 可提现积分：系统奖励积分-已完成提现积分；1奖励；2提现
        if (userId == null){
            return ResponseUtil.unlogin();
        }
        // 是否消费满200
        int result = orderService.countByOrderUserId(userId);
        if (result == 1){
            return ResponseUtil.fail(507,"您还不是有效会员");
        }

        LitemallUser user = userService.findById(userId);
        List<LitemallPointsRecord> pointsRecords = pointsRecordService.selectPointListByType(userId, 1);
        List<LitemallPointsRecord> pointsRecords2 = pointsRecordService.selectPointListByType(userId, 2);
        double xitongPoints = getTotalPointsByList(pointsRecords); // 系统奖励
        double tixianPoints = getTotalPointsByList(pointsRecords2); // 已经完成提现
        double hasPoints = xitongPoints - tixianPoints; // 最多可以提现的积分
        double integral = user.getIntegral();// 总积分余额
        Map<String,Double> returnMap = new HashMap<>();
        double returnpoints = integral - hasPoints >=0 ? hasPoints : integral; // 可提现额度
        returnMap.put("total",integral);
        returnMap.put("ketixian",returnpoints);

        return ResponseUtil.ok(returnMap);
    }

    private double getTotalPointsByList(List<LitemallPointsRecord> records){
        double sum = 0;
        if (records != null && records.size() > 0){
            for (LitemallPointsRecord p : records){
                sum += p.getIntegral();
            }
        }
        return sum;
    }


}